package com.emm.yixun.openapi.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.system.service.UserTokenServiceFacade;


/**
 * 验证是否已经登录，过滤器
 * @author ThinkPad
 *
 */
public class LoginFilter implements Filter {
	
	@Resource(name = "includeNotLoginedUrls")
    private String[] includeNotLoginedUrls;

	@Autowired
	private CacheManager cacheManager;
	
	@Autowired
	private UserTokenServiceFacade userTokenServiceFacade;
    

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse res=(HttpServletResponse) response;
		String requestURI=req.getRequestURI();
		try{
			if(requestURI.indexOf("/emm-openapi/appapi/login") != -1 ||
					requestURI.indexOf("/emm-openapi/appapi/queryProjectRoomInfoList") != -1 ||
					requestURI.indexOf("/emm-openapi/appapi/queryCustomerRoomList") != -1 ||
					requestURI.indexOf("/emm-openapi/appapi/getDictionaryList") != -1  ||
					requestURI.indexOf("/emm-openapi/appapi/getDictionaryListByProjectId") != -1 ||
					requestURI.indexOf("/emm-openapi/appapi/question_add") != -1 
					/*|| requestURI.indexOf("/emm-openapi/appapi/queryProjectInfo") != -1 
					|| requestURI.indexOf("/emm-openapi/appapi/queryAgentInfo") != -1
					|| requestURI.indexOf("/emm-openapi/appapi/queryProjectRelationAgentInfo") != -1
					|| requestURI.indexOf("/emm-openapi/appapi/queryCustomerInfo") != -1
					|| requestURI.indexOf("/emm-openapi/appapi/queryCustomerFollowInfo") != -1*/
					){
				arg2.doFilter(req, res);
			}else if(requestURI.indexOf("/testApi") != -1){
				//测试api
				arg2.doFilter(req, res);
			}else{
				String body = request.getParameter("body");
				JSONObject jb=JSONObject.parseObject(body);
				JSONObject params=jb.getJSONObject("params");
				String userId = (String) params.get("userId");
				String merchantId = (String) params.get("merchantId");
				String token = (String) params.get("token");
				
				//校验当前token是否有效
				Cache  cache = cacheManager.getCache("activeSessionsCache");
				String userId_key = merchantId +userId+"userId";//获取userId缓存key
				String token_key = merchantId +userId+"userId"+token;//获取token缓存key
				Element element_userId = cache.get(userId_key);
				Element element_token = cache.get(token_key);
				JSONObject result = new JSONObject();
				response.setContentType("application/json; charset=utf-8");//处理json返回数据乱码
				
				//验证是否账号权限发生变动
				if(StringUtils.isNotBlank(userId)){
					Response<Boolean> reLoginResponse=userTokenServiceFacade.reLoginCheck(userId);
					if(reLoginResponse.isSuccess() && reLoginResponse.getEntity()){
						result.put("result", ResultEnum.FAILURE.getNo());
						result.put("errorCode", XFUNExceptionCode.USER_PERMISSION_CHANGES.getCode());
						result.put("errorMsg", XFUNExceptionCode.USER_PERMISSION_CHANGES.getDesin());
						response.getWriter().write(result.toJSONString());
						//当返回给客户端，删除需要重新登陆的标示
						userTokenServiceFacade.removeReLogin(userId);
						return;
					}
				}
				
				//无缓存或缓存失效
				if(element_userId == null || element_token == null){
					result.put("result", ResultEnum.FAILURE.getNo());
					result.put("errorCode", XFUNExceptionCode.USER_TOKENERROR.getCode());
					result.put("errorMsg", XFUNExceptionCode.USER_TOKENERROR.getDesin());
					response.getWriter().write(result.toJSONString());
					return;
				}
				//有缓存未失效，但userId与token对应值错误
				String ele_token = (String) element_token.getValue();
				String ele_user = (String) element_userId.getValue();
				if(!userId_key.equals(ele_user) && !token_key.equals(ele_token)){
					result.put("result", ResultEnum.FAILURE.getNo());
					result.put("errorCode", XFUNExceptionCode.USER_TOKENERROR.getCode());
					result.put("errorMsg", XFUNExceptionCode.USER_TOKENERROR.getDesin());
					response.getWriter().write(result.toJSONString());
					return;
				}
				arg2.doFilter(req, res);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
